package com.goteam.lmapp.core.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.goteam.lmapp.core.netty.initializer.CoreServerInitializer;

@Component
public class CoreTCPServer {

	private Logger logger = LoggerFactory.getLogger(CoreTCPServer.class);

	private static final int portNumber = 57878;

	@Autowired
	private CoreServerInitializer coreServerInitializer;

	@PostConstruct
	public void serverStart() throws InterruptedException {
		EventLoopGroup bossGroup = new NioEventLoopGroup(5);
		EventLoopGroup workerGroup = new NioEventLoopGroup(50);
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup);
			b.channel(NioServerSocketChannel.class);
			b.childHandler(coreServerInitializer);
			
			//bind the port and start to accept the incoming connections. 
			ChannelFuture f = b.bind(portNumber).sync();
			if (f.isSuccess()) {
				logger.info("启动Netty服务成功，端口号：" + portNumber);
			}else{
				f.cause().printStackTrace();
			}
			
			//wait until the server socket is closed. 
			f.channel().closeFuture().sync();
		} finally {
			//shutdown server gracefully
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}

	}
}
